﻿using JetBrains.ReSharper.Daemon.CSharp.Stages;
using JetBrains.ReSharper.Daemon.Stages;
using JetBrains.ReSharper.Daemon.Stages.Dispatcher;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using MugenMvvmToolkit.ReSharper.Highlighting;
using MugenMvvmToolkit.ReSharper.Infrastructure;

namespace MugenMvvmToolkit.ReSharper.ViewModels.Analyzers
{
    [ElementProblemAnalyzer(new[] { typeof(IInvocationExpression) },
        HighlightingTypes = new[] { typeof(ViewModelInvalidGetMethodCallHighlighting) })]
    public class ViewModelGetMethodCallAnalyzer : ElementProblemAnalyzerBase<IInvocationExpression>
    {
        #region Overrides of ElementProblemAnalyzer<IInvocationExpression>

        protected override void Run(IInvocationExpression element, ElementProblemAnalyzerData data,
            IHighlightingConsumer consumer)
        {
            var method = element.GetReferenceDeclaredElement<IMethod>();
            if (method == null)
                return;
            bool hasIssue = false;
            if (method.Equals(MethodProvider.ViewModelBaseGetMethod) && element.ArgumentList.Arguments.Count != 0)
            {
                var typeofExpression = element.ArgumentList.Arguments[0].Expression as ITypeofExpression;
                hasIssue = typeofExpression != null &&
                           typeofExpression.ArgumentType.IsOfType(TypeProvider.ViewModelInterface);
            }
            else if ((method.Equals(MethodProvider.ViewModelBaseGetMethodGeneric) ||
                      method.Equals(MethodProvider.ViewModelBaseGetMethodGenericWithName)) && element.TypeArguments.Count != 0)
                hasIssue = element.TypeArguments[0].IsOfType(TypeProvider.ViewModelInterface);
            if (hasIssue)
                consumer.AddHighlighting(new ViewModelInvalidGetMethodCallHighlighting(element));
        }

        #endregion
    }
}